/**
 * @Author: colpu
 * @Date: 2025-03-29 19:38:16
 * @LastEditors: colpu ycg520520@qq.com
 * @LastEditTime: 2025-10-22 13:26:27
 * @
 * @Copyright (c) 2025 by colpu, All Rights Reserved.
 */
/*
 * @Author: colpu
 * @Date: 2025-03-29 19:38:16
 * @LastEditors: colpu ycg520520@qq.com
 * @LastEditTime: 2025-03-29 19:48:52
 *
 * Copyright (c) 2025 by colpu, All Rights Reserved.
 */
import { join } from "node:path";
import _ from "lodash";
import debugFactory from "debug";
const debug = debugFactory("core:loader/mixin/config");
import { loadFile } from "../../utils/index.js";
const resolve = import.meta.resolve;
import { addDirectory } from "../../utils/index.js";
function createArrayMerger(arrayKeys) {
  return function customizer(objValue, srcValue, key) {
    if (_.isArray(objValue) && arrayKeys.includes(key)) {
      return _.union(objValue, srcValue); // 去重合并
    }
  };
}
async function getConfig(target, directory, env) {
  const names = ["index.js", `${env}.js`];
  for (const filename of names) {
    const config = await loadFile(`${directory}/${filename}`);
    _.mergeWith(target, config, createArrayMerger(['middlewares']));
  }
}
export default async function loadConfig(ctx) {
  ctx.timing.time("加载config时间");
  const { root } = ctx;
  const coreConf = await loadFile(resolve("../../config/index.js"));
  const directory = resolve(join(root, "src/config"));
  const target = _.merge(
    {
      root,
    },
    coreConf
  );
  await getConfig(target, directory, ctx.env);
  const modulesConf = addDirectory(join(ctx.root, "src/modules"), 'config');
  for (const dir of modulesConf) {
    await getConfig(target, dir, ctx.env);
  }
  ctx.config = target;
  debug("loadConfig: %s", directory);
  ctx.timing.timeEnd("加载config时间");
}
